Exericse 8: Sentence Capitalization

Directions

Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.

Examples

capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'

Guidelines

Two solutions

1. Array of strings

  • Pseudo code

img

  • Use of JavaScript library functions
  • String.prototype.slice(), String.prototype.toUpperCase(), Array.prototype.join()
  • Use slice(" ") and join(" ") with a space in them

2. Array of characters

  • Pseudo code

img

Solution

In [4]:
function capitalize(str) {
  let words = [];
  for (let word of str.split(" ")){ // split with a space
    words.push(word[0].toUpperCase() + word.slice(1));
  }
  return words.join(" "); // join with a space
}

Alternative solution

In [8]:
function capitalize(str) {
  let result = "";
  for (let i=0; i<str.length;i++){
    if (str[i-1] === " " || i === 0){
      result += str[i].toUpperCase(); //use +=
    } else {
      result += str[i];
    }
  }
  return result;
}
In [9]:
capitalize('a short sentence')
Out[9]:
'A Short Sentence'
In [10]:
capitalize('a lazy fox')
Out[10]:
'A Lazy Fox'
In [11]:
capitalize('look, it is working!')
Out[11]:
'Look, It Is Working!'